<template>
  <div class="container">
    <div class="app-container">
      <div>
        <el-button type="primary" size="middle" @click="onOpenPermissionEditor('add')">添加权限</el-button>
      </div>
      <el-table :data="permissionList" row-key="id" default-expand-all border :header-cell-style="{ backgroundColor: '#f8f9fa' }">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 添加权限：这里添加的是二级权限，当前权限的id作为新添加权限的pid -->
            <el-button v-if="row.type === 1" type="text" @click="onOpenPermissionEditor('add', row)">添加</el-button>
            <!-- 编辑权限 -->
            <el-button type="text" @click="onOpenPermissionEditor('edit', row)">编辑</el-button>
            <el-button type="text" @click="onDeletePermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 权限编辑器弹窗组件 -->
      <PermissionEditor ref="permissionEditorRef" @editSuccess="getPermissionList" />
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, deletePermissionAPI } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import PermissionEditor from './components/PermissionEditor'

export default {
  name: 'Permission',
  components: {
    PermissionEditor // 权限编辑器弹窗组件
  },
  data() {
    return {
      // 权限列表
      permissionList: []
    }
  },
  created() {
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const list = await getPermissionListAPI()
      // 将权限列表转换为树形结构，让二级权限不显示
      this.permissionList = transListToTreeData(list, 0)
    },
    // 打开权限编辑器
    onOpenPermissionEditor(type, row = {}) {
      // 打开权限编辑器
      this.$refs.permissionEditorRef.open(type, { ...row })
    },
    // 删除权限
    async onDeletePermission(id) {
      await this.$confirm('您确定要删除该权限吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await deletePermissionAPI(id)
      this.$message.success('删除成功')
      // 刷新列表
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
</style>
